package com.shicijiaoliu.controller;

import com.shicijiaoliu.pojo.Section;
import com.shicijiaoliu.pojo.result;
import com.shicijiaoliu.service.Sectionservice;
import com.shicijiaoliu.utils.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/section")
@Validated
public class sectioncontroller {

    @Autowired
    private Sectionservice sectionservice;

    @GetMapping("/list")
    public result<Object> list(int countpage, int pagenumber,
                                   @RequestParam(required = false) String name,
                               @RequestParam(required = false) String createtime,
                               @RequestParam(required = false) String updatetime){
        List<Section> sectionlist = sectionservice.findBypage(countpage,pagenumber,name,createtime,updatetime);
        if(sectionlist == null){
            return result.error("获取页大于总页数");
        }else{
            int count = sectionservice.getcount(name,createtime,updatetime);
            Map<String,Object> data = new HashMap<>();
            data.put("total",count);
            data.put("items",sectionlist);
            return result.success(data);}
    }

    @PostMapping("/add")
    public result add(String name,String sd){
        Section section = new Section(name,sd);
        Map<String,Object> userdate = ThreadLocalUtils.getThreadLocal();
        section.setAId( Integer.parseInt(userdate.get("id").toString()));
        section.setCreateTime(LocalDateTime.now());
        section.setUpdateTime(LocalDateTime.now());
        if(sectionservice.findByname(name) == null ){
            sectionservice.add(section);
            return result.success();
        }else {
            return result.error("版块已存在");
        }
    }

    @DeleteMapping("/del/{id}")
    public result del(@PathVariable("id")long id){
        if (sectionservice.findByid(id) == null) {
            return result.error("没有找到该版块");
        } else {
            sectionservice.delByid(id);
            return result.success();
        }
    }

    @PutMapping("/update")
    public result update(String name,String sd,long sId) {
        Section section = new Section(name, sd,sId);
        if (sectionservice.findByid(sId) == null) {
            return result.error("没有找到该版块");
        } else {
            sectionservice.update(section);
            return result.success();
        }
    }


}
